// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)

// 创建仓库 store
const store = new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false,
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false,
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false,
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false,
      },
    ],
  },
  getters: {
    totalPrice(state) {
      return state.goodList
        .filter((item) => item.checked)
        .reduce((sum, item) => {
          return sum + item.price * item.num
        }, 0)
    },
  },
  mutations: {
    changeNum(state, payload) {
      state.goodList[payload.index].num = payload.num
    },
    delGood(state, payload) {
      state.goodList.splice(payload, 1)
    },
    changeChecked(state, payload) {
      state.goodList[payload].checked = !state.goodList[payload].checked
    },
    changeAll(state, payload) {
      state.goodList.forEach((item) => (item.checked = payload))
    },
  },
  actions: {},
})

// 导出仓库
export default store
